<template>
	<div>
		<a-form ref="formRef" :model="formData" :rules="formRules" layout="vertical">
			<a-card title="其他信息" class="form-card">
				<a-row :gutter="16">
					<a-col :span="24">
						<a-form-item label="无犯罪记录证明" name="noCrimeCert">
							<a-upload
								v-model:file-list="noCrimeCertImageList"
								list-type="picture-card"
								accept="image/jpeg,image/png"
								:multiple="true"
								:maxCount="1"
								:before-upload="beforeNoCrimeCertUpload"
								@change="handleNoCrimeCertChange"
								@preview="handlePreview"
								:showUploadList="{ showRemoveIcon: false }"
							>
								<div class="upload-btn">
									<plus-outlined />
									<div style="margin-top: 8px">上传照片</div>
								</div>
							</a-upload>
							<a-button @click="clearNoCrimeCertImages">清空</a-button>
							<div class="photo-count">已上传 {{ noCrimeCertImageList.length }} 张照片</div>
						</a-form-item>
					</a-col>
				</a-row>
				<a-row :gutter="16">
					<a-col :span="24">
						<a-form-item label="征信报告" name="creditReport">
							<a-upload
								v-model:file-list="creditReportImageList"
								list-type="picture-card"
								accept="image/jpeg,image/png"
								:multiple="true"
								:maxCount="1"
								:before-upload="beforeCreditReportUpload"
								@change="handleCreditReportChange"
								@preview="handlePreview"
								:showUploadList="{ showRemoveIcon: false }"
							>
								<div class="upload-btn">
									<plus-outlined />
									<div style="margin-top: 8px">上传照片</div>
								</div>
							</a-upload>
							<a-button @click="clearCreditReportImages">清空</a-button>
							<div class="photo-count">已上传 {{ creditReportImageList.length }} 张照片</div>
						</a-form-item>
					</a-col>
				</a-row>
			</a-card>
		</a-form>

		<!-- 图片预览 -->
		<a-modal v-model:open="previewVisible" :footer="null" @cancel="previewVisible = false" class="image-preview-modal">
			<img alt="预览图片" :src="previewImageSrc" style="width: 100%" />
		</a-modal>
	</div>
</template>

<script setup>
	import { defineEmits, defineProps, reactive, watch } from 'vue'
	import { message } from 'ant-design-vue'
	import { PlusOutlined } from '@ant-design/icons-vue'
	import onboardingRegistryApi from '@/api/hrms/onboarding/registry/onboardingRegistryApi'
	import Promise from 'lodash-es/_Promise'

	const props = defineProps({
		modelValue: {
			type: Object,
			default: () => ({})
		}
	})

	const emit = defineEmits(['update:modelValue'])

	const formRef = ref()
	const previewVisible = ref(false)
	const previewImageSrc = ref('')

	// 表单数据
	const formData = reactive({
		noCrimeCert: '',
		creditReport: '',
		...props.modelValue
	})

	// 照片预览数据
	const noCrimeCertImageList = ref([])
	const creditReportImageList = ref([])
	const jdOssBaseUrl = 'https://s3.cn-north-1.jdcloud-oss.com/'

	// 初始化照片预览数据
	watch(
		() => props.modelValue,
		(newVal) => {
			if (newVal) {
				if (newVal.noCrimeCert) {
					noCrimeCertImageList.value = [
						{
							uid: Date.now(),
							name: newVal.noCrimeCert,
							status: 'done',
							url: `${jdOssBaseUrl}${newVal.noCrimeCert}`
						}
					]
				}
				if (newVal.creditReport) {
					creditReportImageList.value = [
						{
							uid: Date.now(),
							name: newVal.creditReport,
							status: 'done',
							url: `${jdOssBaseUrl}${newVal.creditReport}`
						}
					]
				}
			}
		},
		{ immediate: true, deep: true }
	)

	// 表单验证规则
	const formRules = {
		noCrimeCert: [
			{
				required: true,
				message: '请上传无犯罪记录证明',
				validator: (rule, value) => {
					if (noCrimeCertImageList.value.length === 0) {
						return Promise.reject('请上传身份证照片')
					} else {
						return Promise.resolve()
					}
				},
				trigger: 'change'
			}
		],
		creditReport: [
			{
				required: true,
				message: '请上传征信报告',
				validator: (rule, value) => {
					if (creditReportImageList.value.length === 0) {
						return Promise.reject('请上传征信报告')
					} else {
						return Promise.resolve()
					}
				},
				trigger: 'change'
			}
		]
	}

	const beforeNoCrimeCertUpload = (file) => {
		noCrimeCertImageList.value = noCrimeCertImageList.value.filter((item) => item.originFileObj)
		return false
	}

	const handleNoCrimeCertChange = ({ fileList: newFileList }) => {
		// 去重处理
		const uniqueFiles = []
		const seen = new Set()
		newFileList.forEach((file) => {
			const key = file.uid || file.name
			if (!seen.has(key)) {
				seen.add(key)
				uniqueFiles.push(file)
			}
		})
		noCrimeCertImageList.value = uniqueFiles
	}

	const handlePreview = (file) => {
		previewImageSrc.value = file.url || file.thumbUrl
		previewVisible.value = true
	}

	const clearNoCrimeCertImages = () => {
		noCrimeCertImageList.value = []
		nextTick(() => {
			formRef.value?.validateFields(['noCrimeCert'])
		})
	}

	const beforeCreditReportUpload = (file) => {
		creditReportImageList.value = creditReportImageList.value.filter((item) => item.originFileObj)
		return false
	}

	const handleCreditReportChange = ({ fileList: newFileList }) => {
		const uniqueFiles = []
		const seen = new Set()
		newFileList.forEach((file) => {
			const key = file.uid || file.name
			if (!seen.has(key)) {
				seen.add(key)
				uniqueFiles.push(file)
			}
		})
		creditReportImageList.value = uniqueFiles
	}

	const clearCreditReportImages = () => {
		creditReportImageList.value = []
		nextTick(() => {
			formRef.value?.validateFields(['creditReport'])
		})
	}

	// 暴露保存数据方法给父组件调用
	defineExpose({
		saveData
	})

	// 保存数据方法（供父组件调用）
	async function saveData() {
		try {
			await formRef.value?.validateFields()
			const submitData = new FormData()
			submitData.append(
				'onboardingRegistryEditBo',
				new Blob(
					[
						JSON.stringify({
							noCrimeCert: 'noCrimeCert',
							creditReport: 'creditReport'
						})
					],
					{
						type: 'application/json'
					}
				)
			)
			noCrimeCertImageList.value.forEach((file) => {
				if (file.originFileObj) {
					submitData.append('multipartFileList', file.originFileObj)
				}
			})
			creditReportImageList.value.forEach((file) => {
				if (file.originFileObj) {
					submitData.append('multipartFileList', file.originFileObj)
				}
			})
			await onboardingRegistryApi.updateRegistryInfo(props.modelValue.id, submitData)
			message.success('其他信息保存成功')
			return true
		} catch (error) {
			console.error('表单验证失败:', error)
			if (error.errorFields) {
				// 表单验证错误
				const firstError = error.errorFields[0]
				message.error(`表单填写有误: ${firstError.errors[0]}`)
			} else {
				// 其他错误
				message.error('请上传所有必填的图片')
			}
			return false
		}
	}
</script>

<style scoped>
	.form-card {
		margin-bottom: 16px;
		border-radius: 8px;
	}

	.form-card :deep(.ant-card-head) {
		background-color: #fafafa;
		border-radius: 8px 8px 0 0;
	}

	.photo-preview-item .delete-icon {
		position: absolute;
		top: 4px;
		right: 4px;
		background-color: rgba(0, 0, 0, 0.5);
		color: white;
		border-radius: 50%;
		padding: 2px;
		font-size: 12px;
		cursor: pointer;
	}

	.photo-upload-btn {
		width: 80px;
		height: 80px;
		border: 1px dashed #d9d9d9;
		border-radius: 8px;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		cursor: pointer;
		color: #999;
	}

	.photo-upload-btn:hover {
		border-color: #1890ff;
		color: #1890ff;
	}

	.photo-count {
		margin-top: 8px;
		font-size: 12px;
		color: #999;
	}

	.image-preview-modal :deep(.ant-modal-content) {
		padding: 0;
	}

	.image-preview-modal :deep(.ant-modal-body) {
		padding: 0;
	}
</style>
